package com.install.core.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import com.install.core.service.CommonService;
import com.install.core.service.SpringApplicationContext;
import com.install.core.util.Response;
import com.install.core.util.UserUtil;
import com.install.services.IndexService;
import com.install.services.LoginService;
/***
 * 
 * @author pk 2013-01-15
 *
 */
public class CommonServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public CommonServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			response.setContentType("text/json; charset=utf-8");
			request.setCharacterEncoding("utf-8");
			String serviceName = request.getParameter("serviceName");
			String beanName = serviceName.split("\\.")[0];
			String methodName = serviceName.split("\\.")[1];
			JSONArray paramArray = new JSONArray();
			String ip = request.getHeader("x-forwarded-for");
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0
					|| "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			if(serviceName.indexOf("IndexService.getGns")==0){
				if(request.getParameter("bcondition")!=null){
					Object obj = JSONSerializer.toJSON(request.getParameter("bcondition"));
					if (obj instanceof JSONObject) {
						paramArray.add(obj);
					} else {
						paramArray = (JSONArray) obj;
					}
				}
			}else{
				Object obj = JSONSerializer.toJSON(request
						.getParameter("PARAM"));
	
				if (obj instanceof JSONObject) {
					paramArray.add(obj);
				} else {
					paramArray = (JSONArray) obj;
				}
			}
			UserUtil userUtil = new UserUtil(request);
			String jsonString = null;
			if (userUtil.getUid() == null&&!serviceName.equals("LoginService.login")) {
				Response responseJson = new Response();
				responseJson.setResponse(0, 9000, "会话超时！无法取得用户信息,请重新登录！", null);
				jsonString = responseJson.getRtnJSON();
			} else if(serviceName.equals("LoginService.login")){
				// 取得bean对象实体
				Object object = SpringApplicationContext.getInstance(request.getSession().getServletContext())
						.getBean(beanName);
				Class[] argClasses = new Class[] { JSONArray.class,
						UserUtil.class };
				Method method = object.getClass().getMethod(methodName,
						argClasses);
				Object[] args = new Object[] { paramArray, userUtil };
				// 函数调用
				method.invoke(object, args);
				JSONObject  user=((LoginService) object).getResponse().getRtnObject();
				request.getSession().setAttribute("user", user.get("user"));
				jsonString = ((CommonService) object).getResponseJson();
			}else if(serviceName.indexOf("IndexService.getGns")==0){
				// 取得bean对象实体
				Object object = SpringApplicationContext.getInstance(request.getSession().getServletContext())
						.getBean(beanName);
				Class[] argClasses = new Class[] { JSONArray.class,
						UserUtil.class };
				Method method = object.getClass().getMethod(methodName,
						argClasses);
				Object[] args = new Object[] { paramArray, userUtil };
				// 函数调用
				method.invoke(object, args);
				jsonString = ((IndexService) object).getResponse().getRtnObject().getString("treeList");
			}else{
				// 取得bean对象实体
				Object object = SpringApplicationContext.getInstance(request.getSession().getServletContext())
						.getBean(beanName);
				Class[] argClasses = new Class[] { JSONArray.class,
						UserUtil.class };
				Method method = object.getClass().getMethod(methodName,
						argClasses);
				Object[] args = new Object[] { paramArray, userUtil };
				// 函数调用
				method.invoke(object, args);
				jsonString = ((CommonService) object).getResponseJson();
			}
			PrintWriter out = response.getWriter();
			System.out.println(jsonString);
			out.print(jsonString);
			out.flush();
		} catch (Exception ex) {
			ex.printStackTrace();
			request.setAttribute("message", "Exception:" + ex.getMessage());
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
